package client;

import java.io.*;

public class JabberThread extends Thread {    
    private InputStream inputStream;
    private OutputStream outputStream;
    boolean init = true;

    public JabberThread() {
    }

    public JabberThread(InputStream inputStream, OutputStream outputStream) {
        this.inputStream = inputStream;
        this.outputStream = outputStream;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }
    BufferedReader wr = null;

    public synchronized void test() {
        System.out.println("TESTED");
    }

    public void test2() {
        System.out.println("TESTED");
    }

    public static void test3() {
        System.out.println("TESTED");
    }

    @Override
    public void run() {
        byte[] buffer = new byte[4096];
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Main.socket.getOutputStream(), "UTF8"));
            if (init) {
                writer.write("<stream:stream xmlns:stream='http://etherx.jabber.org/streams' version='1.0' xmlns='jabber:client' to='myflower.cz' xml:lang='cs' xmlns:xml='http://www.w3.org/XML/1998/namespace' >");
                writer.write("<iq type='set' id='prihlaseni001'>  <query xmlns='jabber:iq:auth'>    <username>fel</username>    <password>123456</password>    <resource>JaJa</resource>  </query></iq>");
                writer.write("<message type='chat' to='myflower@myflower.cz' id='myId001' ><body>Testovaci zprava z JaJa klienta...</body></message>");
                writer.write("<presence from='fel@myflower.cz/JaJa' ><show>away</show><status>pryc</status><priority>5</priority><c xmlns='http://jabber.org/protocol/caps' node='http://psi-im.org/caps' ver='caps-b75d8d2b25' ext='ca ep-notify html' /></presence>");
                writer.flush();
                init = false;
            }
            while (true) {
               /* writer = new BufferedWriter(new OutputStreamWriter(Main.socket.getOutputStream(), "UTF8"));
                writer.write("<presence from='fel@myflower.cz/JaJa' ><show>away</show><status>pryc</status><priority>5</priority><c xmlns='http://jabber.org/protocol/caps' node='http://psi-im.org/caps' ver='caps-b75d8d2b25' ext='ca ep-notify html' /></presence>");
                writer.flush(); */
                int pocetBytu = inputStream.read(buffer);
                if (pocetBytu == -1) {
                    break;
                }
                String bufferToString = Main.convByteArrayToString(buffer);
                
                outputStream.write(buffer, 0, pocetBytu);
                outputStream.write(Main.convStrToByteArray("\n\n"));
            }
            System.out.println("\nVýstupní proud byl ukončen.\n");
        }
        catch (Exception e) {
            System.out.println("Chyba 2: " + e + "\n");
            System.exit(-1);
        }
    }
}
